﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Autofac;

namespace Ue.CQRS.Tests
{   
    [TestClass]
    public class AppContextTests
    {
        [TestInitialize]
        public void Initial()
        {
            try
            {
                var context = AppContext.GetContext();
                if (context != null && context.IsStart)
                {
                    context.Stop();
                }
            }
            catch { }
        }

        #region GetContext

        [TestMethod]
        public void IfNotStartShouldThrowException()
        {
            var appContext = new ApplicationContext(null);

            try
            {
                var context = AppContext.GetContext();

                Assert.Fail("当未启动AppContext时应该抛出DomainException异常。");
            }
            catch(DomainException)
            {
            }
        }

        [TestMethod]
        public void GetContext()
        {
            var appContext = new ApplicationContext(null);
            appContext.Start();

            Assert.IsNotNull(AppContext.GetContext());
            Assert.AreEqual(appContext, AppContext.GetContext());
        }

        #endregion
    }

    public class ApplicationContext : AppContext
    {
        private IContainer container;

        public ApplicationContext(ContainerBuilder builder)
        {
            if (builder != null)
            {
                this.container = builder.Build();
            }
        }

        public override T Resolve<T>()
        {
            if (this.container != null)
            {
                return this.container.Resolve<T>();
            }
            else
            {
                return default(T);
            }
        }
    }
}
